package team.zero.lemon.module.cms.service;

import com.sun.org.apache.bcel.internal.generic.NEW;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import team.zero.lemon.common.date.UTC;
import team.zero.lemon.common.exception.CustomException;
import team.zero.lemon.common.persistence.Page;
import team.zero.lemon.common.security.session.SessionContext;
import team.zero.lemon.common.security.session.model.Session;
import team.zero.lemon.common.service.CrudService;
import team.zero.lemon.common.utils.JSEscape;
import team.zero.lemon.common.utils.StreamUtils;
import team.zero.lemon.module.cms.dao.IArticleDao;
import team.zero.lemon.module.cms.dao.IAuditDao;
import team.zero.lemon.module.cms.dao.ICategoryDao;
import team.zero.lemon.module.cms.entity.Article;
import team.zero.lemon.module.cms.entity.ArticleData;
import team.zero.lemon.module.cms.entity.Audit;
import team.zero.lemon.module.cms.entity.Category;
import team.zero.lemon.module.cms.tools.Html;
import team.zero.lemon.module.sys.news.entity.News;
import team.zero.lemon.module.sys.news.service.NewsService;

import javax.servlet.http.HttpServletRequest;
import javax.xml.crypto.Data;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by bolin on 2016/10/24.
 */
@Service
public class ArticleService extends CrudService<IArticleDao, Article> {
    @Autowired
    private AuditService auditService;
    @Autowired
    private NewsService newsService;
    @Autowired
    private ArticleDataServie articleDataServie;

    public Article findByArticleId(Article article) {
        try {
            Article articleMain = dao.findById(article.getId());
            articleMain.setArticleData(articleDataServie.findByArticleId(article.getId()));
            articleMain.setAudits(auditService.findByArticleId(article.getId(), null));
            return articleMain;
        } catch (Exception e) {
            throw new CustomException(e);
        }
    }

    public Page<Article> findViewPage(Article entity) {
        try {
            entity.page.setList(dao.findViewPage(entity));
            return entity.page;
        } catch (Exception e) {
            throw new CustomException(e);
        }
    }

    @Transactional
    public int saveArticle(HttpServletRequest request, Article article) {
        try {
            Session session = SessionContext.getSession();
            if (session == null) {
                article.setUserId(0);
                article.setUserName("未知");
                article.setOrgId(0);
                article.setOrgName("未知");
            } else {
                article.setUserId(session.getId());
                article.setUserName(session.getNikeName());
                article.setOrgId(session.getOrgId());
                article.setOrgName(session.getOrgName());
            }
            article.setAuditTime(UTC.date());
            article.setAuditUserId(article.getUserId());
            article.setAuditStatus(1);
            int articleId = save(article);
            if (!article.isInsert()) {
                articleId = article.getId();
            }
            ArticleData articleData = article.getArticleData();
            articleData.setArticleId(articleId);
            articleDataServie.save(articleData);
            List<Audit> audits = article.getAudits();
            auditService.deleteByArticleId(articleId);
            List<Integer> userIds = new ArrayList<Integer>();

            for (Audit audit : audits) {
                if (audit.getAuditType() == 1) {
                    userIds.add(audit.getAuditId());
                } else {

                }
                audit.setArticleId(articleId);
                audit.setInsert(true);
                auditService.save(audit);
            }
//          newsService.send(article.getTitle(),articleId,article.getCategoryId(),"/views/cms/info/"+articleId+".html",article.getUserId(),article.getUserName(),userIds);
            createHtml(request, article.getId().toString(), article.getTitle(), article.getUserName(), article.getOrgName(), article.getCategoryName(), article.getAuditTime(), articleData.getContent());
            return articleId;

        } catch (Exception exc) {
            throw new CustomException(exc.getMessage());
        }
    }

    private boolean createHtml(HttpServletRequest request, String id, String title, String userName, String orgName, String CategroryName, Date auditTime, String content) {
        try {
            String path = request.getRealPath("/views/cms");
            String templateHtml = path + File.separator + "temp/temp.html";
            String savePath = path + File.separator + "info";
            String fileName = id + ".html";
            Map map = new HashMap<String, String>();
            map.put("title", title);
            map.put("userName", "发布人：" + userName);
            map.put("orgName", "发布处室：" + orgName);
            map.put("CategroryName", "类别：" + CategroryName);
            map.put("CategroryName", "类别：" + CategroryName);
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");

            String dateString = formatter.format(auditTime);
            map.put("auditTime",dateString);

            map.put("content", JSEscape.unescape(content));
            Html.Create(templateHtml, savePath, fileName, map);
            return true;
        } catch (Exception exc) {
            throw new CustomException(exc.getMessage());
        }
    }

}
